<route lang="yaml">
meta:
enabled: false
</route>

<script setup lang="ts">
import type { Suggestions } from '@/api/modules/suggestions'
import type { FormInstance, FormRules } from 'element-plus'
import apiSuggestion from '@/api/modules/suggestions'
import useSettingsStore from '@/store/modules/settings'
import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const updateImg = ref(false)
const route = useRoute()
const router = useRouter()
const tabbar = useTabbar()
const settingsStore = useSettingsStore()
const loading = ref(false)
const formRef = ref<FormInstance>()
const form = ref({
  suggestionId: route.params.id as string | number ?? '',
  suggestionsTitle: '',
  suggestionContent: '',
  suggestionContentEn: '',
  userId: '',
  suggestType: '',
  suggestionFeedback: '',
  suggestionFeedbackEn: '',
  infringementUrl: '',
  url: '',
  createdAt: '',
  feedbackTime: '',
  status: 0, // 默认值为 "否"
  nickName: '',
  telephone: '',
  showInfringementFields: false, // 控制侵权字段的显示
  uid: '',
})

// 建议类型映射
const SUGGESTION_TYPE_MAP = {
  2: '建议',
  1: '投诉',
} as const

// 获取建议类型的中文描述
const getSuggestionTypeLabel = (value: '2' | '1') => {
  return SUGGESTION_TYPE_MAP[value] || '未知'
}

// 表单规则
const formRules = ref<FormRules>({
  suggestionsTitle: [
    { required: true, message: '请输入建议标题', trigger: 'blur' },
    { max: 20, message: '建议标题长度不能超过20个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        // 允许字母、数字、汉字、空格、基本标点和中英文逗号
        if (/[#%&?]/.test(value)) {
          callback(new Error('不允许输入特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  suggestionContent: [
    { required: true, message: '请输入建议内容', trigger: 'blur' },
    { max: 200, message: '建议内容长度不能超过200个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        // 允许字母、数字、汉字、空格、基本标点和中英文逗号
        if (/[#%&?]/.test(value)) {
          callback(new Error('不允许输入特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  suggestType: [
    { required: true, message: '请选择建议类型', trigger: 'blur' },
  ],
  suggestionFeedback: [
    { max: 200, message: '建议反馈长度不能超过100个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        // 允许字母、数字、汉字、空格、基本标点和中英文逗号
        if (/[#%&?]/.test(value)) {
          callback(new Error('不允许输入特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  infringementUrl: [
    {
      validator: (_, value, callback) => {
        if (!/^https?:\/\/.+\..+/.test(value)) {
          callback(new Error('请输入有效的网址'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  telephone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: any) => { // 添加下划线表示忽略
        const phoneRegex = /^1[3-9]\d{9}$/
        if (!phoneRegex.test(value)) {
          callback(new Error('电话号码格式不正确'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],

})

onMounted(() => {
  if (form.value.suggestionId !== '') {
    getInfo()
  }
})

function getInfo() {
  loading.value = true
  apiSuggestion.detail(form.value.suggestionId).then((res: any) => {
    console.log(res)
    loading.value = false
    const data = res.data.data // 提取数据
    // 完整映射所有字段
    form.value.suggestionId = data.suggestionId
    form.value.suggestionsTitle = data.suggestionsTitle
    form.value.suggestionContent = data.suggestionContent
    form.value.suggestionContentEn = data.suggestionContentEn
    form.value.userId = data.userId
    form.value.suggestType = getSuggestionTypeLabel(data.suggestType)
    form.value.suggestionFeedback = data.suggestionFeedback
    form.value.suggestionFeedbackEn = data.suggestionFeedbackEn
    form.value.infringementUrl = data.infringementUrl
    form.value.url = data.url
    form.value.createdAt = data.createdAt
    form.value.feedbackTime = data.feedbackTime
    form.value.status = data.status
    form.value.nickName = data.nickName
    form.value.telephone = data.telephone
    form.value.uid = data.uid
  })
}

function onSubmit() {
  return new Promise<void>(() => {
    formRef.value?.validate((valid) => {
      if (valid) {
        // 确保 status 有值，默认为 0
        const statusValue = form.value.status !== null ? form.value.status : 0

        // 将建议类型中文描述转换回数字
        const suggestTypeValue = Object.keys(SUGGESTION_TYPE_MAP).find(
          key => SUGGESTION_TYPE_MAP[key as '2' | '1'] === form.value.suggestType,
        ) || '1'

        // 构造符合 Suggestions 接口的对象并提交
        const suggestionData: Suggestions = {
          suggestionId: Number(form.value.suggestionId),
          suggestionsTitle: form.value.suggestionsTitle,
          suggestionContent: form.value.suggestionContent,
          suggestionContentEn: form.value.suggestionContentEn,
          userId: Number(form.value.userId),
          suggestType: suggestTypeValue,
          suggestionFeedback: form.value.suggestionFeedback,
          suggestionFeedbackEn: form.value.suggestionFeedbackEn,
          infringementUrl: form.value.infringementUrl,
          url: form.value.url,
          createdAt: form.value.createdAt,
          feedbackTime: form.value.feedbackTime,
          status: statusValue.toString(),
          nickName: form.value.nickName,
          telephone: form.value.telephone,
        }

        if (form.value.suggestionId === '') {
          apiSuggestion.create(suggestionData).then(() => {
            ElMessage.success({
              message: '新增成功',
            })
            goBack()
          })
        }
        else {
          form.value.suggestionId = Number(form.value.suggestionId)
          apiSuggestion.edit(suggestionData).then(() => {
            ElMessage.success({
              message: '编辑成功',
            })
            goBack()
          })
        }
      }
    })
  })
}

function onCancel() {
  goBack()
}
// 返回列表页
function goBack() {
  if (settingsStore.settings.tabbar.enable && settingsStore.settings.tabbar.mergeTabsBy !== 'activeMenu') {
    tabbar.close({ name: 'suggestion' })
  }
  else {
    router.push({ name: 'suggestion' })
  }
}

// 上传证明材料图片
async function infringing(file: any) {
  updateImg.value = true
  const formData = new FormData()
  formData.append('file', file.file)
  return await apiSuggestion.uploadAvatar(formData).then((res: any) => {
    updateImg.value = false
    if (res.code === 200) {
      form.value.url = res.data
      ElMessage.success({
        message: '上传成功',
      })
    }
  })
}
</script>

<template>
  <div class="absolute size-full flex flex-col">
    <FaPageHeader :title="route.name === 'suggestionCreate' ? '新增建议' : '编辑建议'" class="mb-0">
      <ElButton size="default" round @click="goBack">
        <template #icon>
          <FaIcon name="i-ep:arrow-left" />
        </template>
        返回
      </ElButton>
    </FaPageHeader>
    <ElForm ref="formRef" :model="form" :rules="formRules" label-width="130px" label-suffix="：" class="custom-form">
      <FaLayoutContainer right-side-width="500px" hide-right-side-toggle class="static" right-side-class="flex flex-col">
        <ElFormItem
          v-if="route.name !== 'suggestionCreate'"
          label="建议用户"
          prop="nickName"
        >
          <ElInput v-model="form.nickName" :disabled="true" />
        </ElFormItem>

        <!-- 建议内容 -->
        <ElFormItem label="建议标题" prop="suggestionsTitle">
          <ElInput
            v-model="form.suggestionsTitle"
            placeholder="请输入建议标题"
          />
        </ElFormItem>

        <ElFormItem label="建议内容" prop="suggestionContent">
          <ElInput
            v-model="form.suggestionContent"
            placeholder="请输入建议内容"
          />
        </ElFormItem>

        <!-- 建议类型 -->
        <ElFormItem label="建议类型" prop="suggestType">
          <ElSelect
            v-model="form.suggestType"
            placeholder="请选择建议类型" style="width: 100%;"
          >
            <ElOption label="投诉" value="1" />
            <ElOption label="建议" value="2" />
          </ElSelect>
        </ElFormItem>

        <!-- 建议反馈 -->
        <ElFormItem label="建议反馈" prop="suggestionFeedback">
          <ElInput
            v-model="form.suggestionFeedback"
            placeholder="请输入建议反馈"
          />
        </ElFormItem>

        <!-- 侵权网址 -->
        <ElFormItem label="侵权网址" prop="infringementUrl">
          <ElInput
            v-model="form.infringementUrl"
            placeholder="请输入侵权网址"
          />
        </ElFormItem>

        <!-- 证明材料图片 -->
        <ElFormItem label="证明材料图片" prop="url">
          <ImageUpload
            v-model="form.url"
            :loading="updateImg"
            action=""
            name="url"
            :width="150"
            :height="150"
            :http-request="infringing"
          />
        </ElFormItem>

        <!-- 手机号 -->
        <ElFormItem label="手机号" prop="telephone">
          <ElInput
            v-model="form.telephone"
            placeholder="请输入手机号"
          />
        </ElFormItem>

        <!-- 是否解决 -->
        <ElFormItem label="是否解决" prop="status">
          <ElSwitch
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否"
            inline-prompt
          />
        </ElFormItem>

        <FaFixedActionBar>
          <ElButton type="primary" size="large" @click="onSubmit">
            提交
          </ElButton>
          <ElButton size="large" @click="onCancel">
            取消
          </ElButton>
        </FaFixedActionBar>
      </FaLayoutContainer>
    </ElForm>
  </div>
</template>

<style scoped>
.custom-form {
  display: flex;
  flex: 1;
  overflow: auto;
}
</style>
